package org.pih.javarosa.activity.countryList;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import org.javarosa.core.util.OrderedHashtable;
import org.javarosa.j2me.log.CrashHandler;
import org.javarosa.j2me.log.HandledCommandListener;
import org.javarosa.j2me.view.J2MEDisplay;
import org.pih.javarosa.util.AdultDosageUtil;

public class CountryListController implements HandledCommandListener {
	CountryListTransitions transitions;
	CountryListView view;

	OrderedHashtable countries;

	public CountryListController() {
		countries = AdultDosageUtil.getCountryList();

		Vector countryNames = new Vector();
		for (Enumeration e = countries.elements(); e.hasMoreElements();){
			countryNames.addElement(e.nextElement());
		}
			

		view = new CountryListView("Countries", countryNames);
		view.setCommandListener(this);
	}

	public void setTransitions(CountryListTransitions transitions) {
		this.transitions = transitions;
	}

	public void start() {
		J2MEDisplay.setView(view);
	}

	public void commandAction(Command c, Displayable d) {
		CrashHandler.commandAction(this, c, d);
	}  

	public void _commandAction(Command c, Displayable d) {
		if (d == view) {
			if (c == view.CMD_EXIT) {
				transitions.exit();
			} else if (c == view.CMD_ABOUT) {
				transitions.about();
			} else if (c == view.CMD_VIEW_SAVED) {
				int index = view.getSelectedIndex();
				if (index != -1)
					transitions.countrySelected(((Integer)countries.keyAt(index)).intValue());
			} else if (c == List.SELECT_COMMAND) {
				int index = view.getSelectedIndex();
				if (index != -1)
					transitions.countrySelected(((Integer)countries.keyAt(index)).intValue());
			} 
		}
	}
}
